package com.baidu.bulls.stock.cat.demo.order.startup;

import com.baidu.bulls.stock.cat.demo.order.catutils.CatRestInterceptor;
import com.dianping.cat.Cat;
import com.dianping.cat.CatConstants;
import com.dianping.cat.message.Transaction;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;

@SpringBootApplication
@EnableDiscoveryClient
@ComponentScan(basePackages = {"com.baidu"})
@RestController
@Log4j2
public class CatDemoOrderApplication {

    @Bean
    RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        // 保存和传递调用链上下文
        restTemplate.setInterceptors(Collections.singletonList(new CatRestInterceptor()));
        return restTemplate;
    }

    @Autowired
    private RestTemplate restTemplate;
    @Value("${server2.account:localhost:8083}")
    private String service2account;
    @Value("${server2.stock:localhost:8084}")
    private String service2stock;

    private static final int MOCK_PORT = 5555;

    public static void main(String[] args) {
        SpringApplication.run(CatDemoOrderApplication.class,args);
    }

    @RequestMapping("/order")
    public String order() throws InterruptedException {
        Thread.sleep(200);
        String url1 = "http://" + service2account + "/account";
        String url2 = "http://" + service2stock + "/stock";

        String result1 = restTemplate.getForObject(url1, String.class);
        String result2 = restTemplate.getForObject(url2, String.class);
        return "order result =====》》》》" +result1+","+result2;
    }

    //超时
    @RequestMapping("/timeout")
    public String connectTimeout() throws InterruptedException {
        Transaction t = Cat.newTransaction(CatConstants.TYPE_REMOTE_CALL, "connectTimeout");
        Thread.sleep(300);

        try {
            log.info("colling  a miss service{}" ,MOCK_PORT);
            String result = restTemplate.getForObject("http://localhost:" + MOCK_PORT + "/timeout", String.class);
            return result;
        } catch (Exception exception) {
            t.setStatus(exception);
            Cat.logError(exception);
            log.error(exception);
            throw exception;
        } finally {
            t.complete();
        }

    }


}
